<?php
namespace Twoir\Service\Member;

use Exception;
use Twoir\Service\BaseMember;
use Twoir\System\Model\EnewsMember;

/**
 * 会员登陆
 *
 * 2024.05.01 cighsen02 3651872575
 * Update at: 2025.05.08
*/
class Login extends BaseMember
{
	// 允许进入字段
	const ALLOW = ['username', 'password', 'email', 'phone', 'lifetime'];
	// 验证码key名称
	const LONGIN_KEY_NAME = 'checkloginkey';

    public function __construct()
    {
        parent::__construct(false);
    }

	/**
	 * 邮箱注册
	 *
	 * @param array $add
	 * @return array
	*/
	public function email($add)
	{
		// 参数过滤
		$add = $this->paramFilter($add);

		return [];
	}

	/**
	 * 用户名注册
	 *
	 * @param array $add
	 * @return array
     *
     * @throws Exception
	*/
	public function userName(array $add): array
	{
	    global $public_r, $level_r, $ecms_config;
		// 参数过滤
		$add = $this->paramFilter($add);

		$username	= isset($add['username']) && $add['username'] ? trim($add['username']) : null;
		$password	= isset($add['password']) && $add['password'] ? trim($add['password']) : null;

		if(!$username || !$password) throw new Exception('用户名和密码不能为空', 9200);
		//验证码
		if($public_r['loginkey_ok']){

			if (!isset($add['key']) || empty($add['key'])) throw new Exception('验证码不能为空', 9200);

			$this->checkShowKey(static::LONGIN_KEY_NAME, $add['key'], 1);
		}

		$username	= RepPostVar($username);
		$password	= RepPostVar($password);

		if (empty($user = EnewsMember::getOne(['username' => $username], ['userid','password','groupid','checked','rnd','salt','rndt','registertime'])) || !$this->doCkMemberPw($password, $user['password'], $user['salt'])) {

			throw new Exception('用户名不存在或密码错误', 9200);
		}

        //默认会员组
		if(empty($user['groupid'])) $user['groupid'] = eReturnMemberDefGroupid();

        $user['groupid'] = (int)$user['groupid'];

        if($level_r[$user['groupid']]['loginps'] && $level_r[$user['groupid']]['loginps'] !== $add['mg_loginps'])
        {
            throw new Exception('认证码不对', 9200);
        }

		if(0 == $user['checked']){

			if(1 == $public_r['regacttype']){

				throw new Exception('用户还未激活，请通过邮件激活', 9200);
			}

			throw new Exception('用户还未审核，请耐心等待', 9200);
		}

        $eipf       = egetipfrom();
		$lastip		= egetip(); // IP
		$lastipport	= egetipport();
		$rnd		= $ecms_config['sets']['mpchmrnd'] ? make_password(EcmsRandInt(20,36)) : $user['rnd'];// 取得随机密码
        $rndt       = $ecms_config['sets']['mpchmrnd'] ? make_password(EcmsRandInt(20,32)) : $user['rndt'];

        $update = [
            'rnd'           => $rnd,
            'rndt'          => $rndt,
            'groupid'       => $user['groupid'],
            'lasttime'      => $this->nowtime,
            'lastip'        => $lastip,
            'loginnum'      => 'loginnum + 1',
            'lastipport'    => $lastipport,
            'isot'          => 1,
            'eipf'          => $eipf
        ];

		// 执行更新
		EnewsMember::update(['userid' => $user['userid']], $update);

		//设置cookie
		$lifetime 	= isset($add['lifetime']) ? (int)$add['lifetime'] : 0;
		$logincookie= 0;
		if($lifetime) $logincookie = $this->nowtime + $lifetime;

		esetcookie('mlusername', $username, $logincookie);
		esetcookie('mluserid', $user['userid'], $logincookie);
		esetcookie('mlgroupid', $user['groupid'], $logincookie);
		esetcookie('mlrnd', $rnd, $logincookie);
        esetcookie("mlrndt", $rndt, $logincookie);
		$this->qGetLoginAuthstr($user['userid'], $username, $rnd, $user['groupid'], $logincookie);
		//清空验证码
		$this->emptyShowKey(static::LONGIN_KEY_NAME);
		esetcookie('returnurl', '');

		// 移除
		unset($user['password'], $user['salt']);

		return $user + [
			'username' => $username
		];
	}

	/**
	 * 手机注册，在做之前请在主表增加phone字段
	 *
	 * @param array $add
	 * @return array|throw
	*/
	public function phone($add)
	{
		// 参数过滤
		$add = $this->paramFilter($add);

		return [];
	}

	/**
	 * 验证密码
	 *
	 * @param string $newPassWord
	 * @param string $oldPassWord
	 * @param string $salt
	 * @return bool
	*/
	protected function doCkMemberPw(string $newPassWord, string $oldPassWord, string $salt): bool
	{
		global $ecms_config;

		if(0 == $ecms_config['member']['pwtype'])// 单重md5
		{
			if(md5($newPassWord) === $oldPassWord) return true;
		}
		elseif(1 == $ecms_config['member']['pwtype'])// 明码
		{
			if($newPassWord === $oldPassWord) return true;
		}
		elseif(3 == $ecms_config['member']['pwtype'])// 16位md5
		{
			if(substr(md5($newPassWord), 8, 16) === $oldPassWord) return true;
		}
		else// 双重md5
		{
			if(md5(md5($newPassWord) . $salt) === $oldPassWord) return true;
		}

		return false;
	}
}
